package com.cw.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.cw.mp.domain.dto.PageDTO;
import com.cw.mp.domain.dto.UserFormDTO;
import com.cw.mp.domain.po.User;
import com.cw.mp.domain.vo.UserVO;
import com.cw.mp.query.UserQuery;
import com.cw.mp.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/users")
//@RequiredArgsConstructor // 必要构造方法
public class UserController {

    private final UserService userService; // 依赖注入新方法
    /*@Autowired*/
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation("新增用户接口")
    @PostMapping
    public void add(@RequestBody UserFormDTO userFormDTO) {
        // 1. 把DTO拷贝到PO
        User user = BeanUtil.copyProperties(userFormDTO, User.class);
        // 2. 新增
        userService.save(user);
    }

    @ApiOperation("删除用户接口")
    @PostMapping("{id}")
    public void deleteUserById(@ApiParam("用户id") @PathVariable("id") Long id) {
        userService.removeById(id);
    }

    @ApiOperation("根据id查询用户接口")
    @GetMapping("{id}")
    public UserVO queryUserById(@ApiParam("用户id") @PathVariable("id") Long id) {
        return userService.queryUserAndAddressById(id);
    }

    @ApiOperation("根据id批量查询用户接口")
    @GetMapping
    public List<UserVO> queryUserById(@ApiParam("用户id集合") @RequestParam("ids") List<Long> ids) {
        return userService.queryUserAndAddressByIds(ids);
    }

    @ApiOperation("根据id扣减余额接口")
    @PutMapping("{id}/deduction/{money}")
    public void deductionBalanceById(
            @ApiParam("用户id") @PathVariable("id") Long id,
            @ApiParam("扣减金额") @PathVariable("money") Long money) {
        userService.deductionBalance(id,money);
    }

    @ApiOperation("复杂查询用户接口")
    @GetMapping("/list")
    public List<UserVO> queryUser(UserQuery userQuery) {
        // 1. 查询用户PO
        List<User> users = userService.queryUsers(
                userQuery.getName(),
                userQuery.getStatus(),
                userQuery.getMinBalance(),
                userQuery.getMaxBalance());
        // 2. 把PO拷贝到VO
        return BeanUtil.copyToList(users, UserVO.class);
    }


    @ApiOperation("根据条件分页查询用户接口")
    @GetMapping("/page")
    public PageDTO<UserVO> queryUserPage(UserQuery userQuery) {
        return userService.queryUsersPage(userQuery);
    }

}
